package cn.news.service;

import cn.news.dao.DetailMapper;

import cn.news.pojo.Detail;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class DetailServiceImpl implements  DetailService{

    @Resource
    private DetailMapper dm;

    @Override
    public List getNews(Integer categoryId, String title) {
        Jedis jedis=new Jedis("127.0.0.1");
        List list=new ArrayList();
        Map<String,String> all=jedis.hgetAll("detail");

        if(all.size()==0) {
            List<Detail> dlist=dm.getNews(categoryId,null);

            for (Detail d:dlist){
                jedis.hset("detail",d.getId().toString(), JSON.toJSONString(d));
            }
        }
        all=jedis.hgetAll("detail");
        Iterator<Map.Entry<String, String>> entries = all.entrySet().iterator();
        while(entries.hasNext()){
            Map.Entry<String,String> entry =entries.next();
            String key=entry.getKey();
            String value=entry.getValue();
            Detail d= JSON.parseObject(value,Detail.class);
            list.add(d);
        }
        jedis.close();
        return list;
    }

    @Override
    public Detail getById(Integer id) {
        return dm.getById(id);
    }

    @Override
    public int update(Detail detail) {
        return dm.update(detail);
    }
}
